#include "UdpClient.hpp"
#include "Thread.hpp"
#include <fcntl.h>    // 包含 open 函数
#include <unistd.h>   // 包含 write 和 close 函数
#include <sys/stat.h> // 包含 open 函数的权限设置
#include <stdio.h>
#include <stdlib.h>

using namespace ThreadModule;

int gsocketfd = -1;

void func(std::string s)
{
    int fd = open("test.txt", O_WRONLY | O_CREAT, 0644);
    dup2(fd, 1);
    while (1)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int n = ::recvfrom(gsocketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "recvfrom error...";
        }
        buffer[n] = 0;

        std::cout << "收到的数据：" << buffer<<std::endl;
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " serverip serverport" << std::endl;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    gsocketfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    Thread th(func);

    th.Start();

    struct sockaddr_in server_addr;
    ::bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_port = ::htons(serverport); // 端口号
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(serverip.c_str()); // 绑定到所有可用网络端口
    std::string message = "加入聊天";
    int n = ::sendto(gsocketfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (n < 0)
    {
        LOG(LogLevel::ERROR) << "sendto error...";
    }

    while (1)
    {
        std::cout << "Please Enter# ";
        std::getline(std::cin, message);
        int n = ::sendto(gsocketfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "sendto error...";
        }
    }

    th.Join();

    // UdpCilent uc(serverip,serverport);
    // uc.InitClient();
    // uc.Start();
    return 0;
}